/*
 * @lc app=leetcode.cn id=82 lang=java
 *
 * [82] 删除排序链表中的重复元素 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if ( head == null || head.next == null){
            return head;
        }
        if ( head.val == head.next.val && head.next.next == null){
            return head.next.next;
        }
        ListNode beforeHead = new ListNode(0);
        beforeHead.next = head;
        ListNode beforeHeadD = beforeHead;
        int target = 0; //标记，是否存在重复元素
        ListNode temp = head;
        while (temp.next != null){
            if ( temp.val == temp.next.val){
                target = 1;
            }else{
                if ( target == 1){
                    beforeHead.next = temp.next;
                    target = 0;
                }else {
                    beforeHead = beforeHead.next;
                }
            }
            temp = temp.next;
        }
        if (target == 1){
            beforeHead.next = temp.next;
        }
        return beforeHeadD.next;
    }
}
// @lc code=end

